//
//  MainViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/19.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
import SwiftyJSON

class MainViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {

    let myTableView = UITableView(frame: CGRect(x: 0, y: 64+SCREEN_HEIGHT*0.08, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.92-64), style: .grouped)
    let MAINTABLEVIEWCELL = "MainTableViewCell"
    let dataArray = NSMutableArray(capacity: 0)
    let searchTextField = UITextField()
    
    var shoppingCarNumber = ""
    
    var mySearchView = UIView()
    let countLabel = UILabel()

    
    let productVCTitleArray = ["AIR JORDAN 12","YEEZY BOOST 350","ADIDAS NMD RUNNER","NIKE AIR HUARACHE","NIKE AIR MAX 90","NIKE ROSHE ONE FLYKNIT"]
    let searchArr = ["yeezy","750","550","350","max 2017","nmd","max 90","boost"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.automaticallyAdjustsScrollViewInsets = false

        //检查更新
        self.isUpdate()
        
        self.creatCountLabel()

        self.getData()
        self.getShoppongCartData()
        self.creatView()
        self.creatSearchView()
        
        
        let center = NotificationCenter.default
        center.addObserver(self, selector: #selector(refreshTableView), name: NSNotification.Name(rawValue: "letHomePageToRefresh"), object: nil)
        center.addObserver(self, selector: #selector(refreshTableView), name: NSNotification.Name(rawValue: "LoginMakeMainVCRefresh"), object: nil)
        
        
    
    }
    func refreshTableView(){
        self.myTableView.mj_header.beginRefreshing()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        sideMenuViewController()?.menuContainerView?.allowPanGesture = true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension MainViewController{
    
    fileprivate func isUpdate(){
        
        let infoDic = Bundle.main.infoDictionary as? NSDictionary
        let currentVersion = infoDic?["CFBundleShortVersionString"] as! String
        
        
        
        let responseData : Data? = try! NSURLConnection.sendSynchronousRequest(URLRequest(url: URL(string: "http://itunes.apple.com/cn/lookup?id=\(APPID)")!), returning : nil)
        
        
        
        if responseData == nil {
            print("no connect network!")
            return
        }
        
        
        do{
            
            let appInfoDic = try JSONSerialization.jsonObject(with: responseData!, options: .mutableLeaves) as? NSDictionary
            
            let array = appInfoDic?["results"] as? NSArray

            if array?.count == 0 {
                return
            }
            let appVersionString = (array?.firstObject as? NSDictionary)?["version"] as! String
            print("current version:\(currentVersion) app's version:\(appVersionString)")
            
            
            let currentVersionNumber : Float = Float(currentVersion.replacingOccurrences(of: ".", with: ""))!

            let appVersionNumber : Float = Float(appVersionString.replacingOccurrences(of: ".", with: ""))!
            
            
            
            if currentVersionNumber < appVersionNumber{
                
                
                let alertController = UIAlertController(title: "Version update", message: "New version detected(\(appVersionString)),Whether to update?", preferredStyle: .alert) // 这里因为控件都不存在改变的可能，所以一律使用let类型.UIAlertControllerStyle可以选择.actionSheet或.alert
                
                let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "Update", style: .default, handler:{
                    (UIAlertAction) -> Void in
                    let url = NSURL(string: "https://itunes.apple.com/us/app/id\(APPID)?ls=1&mt=8")
                    UIApplication.shared.openURL(url as! URL)
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)// 当添加的UIAlertAction超过两个的时候，会自动变成纵向分布
                self.present(alertController, animated: true, completion: nil)
                

                
                
            }else{
                print("the current version is bigger than the app's version")
            }
            
            
        }catch{
            if error != nil {
                print("hsUpdateAppError:\(error)")
                return
            }
        }
        
        
        
        
        
    }
    

    
}


extension MainViewController{
    
    
    
    fileprivate func getData(){
        let parma = ["main_page":"index_banner"]
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                print(result)
                let dic = result as? NSDictionary
                let array = dic!["data"]as?[[String:NSObject]]
                for dict in array!{
                    let mainModel = MainDataModel(dict: dict)
                    self.dataArray.add(mainModel)
                }
                
                self.myTableView.reloadData()
                SVProgressHUD.showSuccess(withStatus: "Load successfully!")
                self.myTableView.mj_header.endRefreshing()
                
            }else{
                SVProgressHUD.showError(withStatus: "Get MainData error" + String(describing: error))
                print("Get MainData error" + String(describing: error))
            }
        }
        
    }
    
    
    fileprivate func getShoppongCartData(){
        if UserSession.shareInstance.cookie != nil {
            let parma = ["main_page":"shopping_cart","zenid":UserSession.shareInstance.cookie!]
            NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parma as [String : NSObject], finishedBlock: { (result, error) in
                if result != nil{
//                    let json = JSON(result!)
//                    print(json)
//                    
                    let dic = ((result as? NSDictionary)!["data"])as?NSDictionary
                    let cartArr = dic!["cart"]as!NSArray
                    self.shoppingCarNumber = String(cartArr.count)
                    self.makeNavWithCount(self.shoppingCarNumber)
                }else{
                    SVProgressHUD.showError(withStatus: "get shopping count error:" + String(describing: error))
                    print("get shopping count error:" + String(describing: error))
                }
            })
            
        }
    }
    
    
    func makeNavWithCount(_ count:String){
        if count != "0" {
            countLabel.text = count
            countLabel.isHidden = false
        }else{
            countLabel.isHidden = true
        }
        
    }
    func creatCountLabel(){
        countLabel.frame = CGRect(x: 22.5, y: 2, width: 20, height: 20)
        countLabel.layer.cornerRadius = 10
        countLabel.layer.masksToBounds = true
        countLabel.backgroundColor = UIColor(red: 241/255.0, green: 42/255.0, blue: 44/255.0, alpha: 1)
        countLabel.textColor = UIColor.white
        countLabel.font = UIFont.systemFont(ofSize: 12)
        countLabel.textAlignment = .center
        self.navigationItem.rightBarButtonItem?.customView?.addSubview(countLabel)
        countLabel.isHidden = true
    }
    
}
extension MainViewController{
    fileprivate func creatSearchView(){
        
        mySearchView.frame = CGRect(x: 0, y: 64+SCREEN_HEIGHT*0.08, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.2)
        mySearchView.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 0.96)
        mySearchView.isHidden = true
        self.view.addSubview(mySearchView)
        
        let imageView = UIImageView()
        imageView.frame = CGRect(x: 5, y: 3, width: SCREEN_HEIGHT*0.2*0.2, height: SCREEN_HEIGHT*0.2*0.2)
        imageView.image = UIImage(named: "search_icon")
        mySearchView.addSubview(imageView)
        
        let label = UILabel()
        label.frame = CGRect(x: SCREEN_HEIGHT*0.2*0.2+15, y: 3, width: SCREEN_WIDTH*0.5, height: SCREEN_HEIGHT*0.2*0.2-6)
        label.text = "HOT SEARCHES"
        label.textColor = UIColor.gray
        mySearchView.addSubview(label)
        
        for i in 0..<searchArr.count{
            let searchBtn = UIButton(type: .custom)
            searchBtn.backgroundColor = UIColor.white
            searchBtn.setTitle(searchArr[i], for: UIControlState())
            if UIScreen.main.bounds.size.width == 320 {
                searchBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            }else{
                searchBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            }
            let height = (SCREEN_HEIGHT*0.2*0.8-15)/2
            let width = (SCREEN_WIDTH-30)/5
            searchBtn.tag = i
            searchBtn.frame = CGRect(x: 5+(width+5)*CGFloat(i%5), y: SCREEN_HEIGHT*0.2*0.2+5+(height+5)*CGFloat(i/5), width: width, height: height)
            searchBtn.layer.cornerRadius = 8.0
            searchBtn.clipsToBounds = true
            searchBtn.setTitleColor(UIColor.black, for: UIControlState())
            searchBtn.addTarget(self, action: #selector(searchButtonArrayClick(_:)), for: .touchUpInside)
            mySearchView.addSubview(searchBtn)
            
        }
       
    }
    
    func searchButtonArrayClick(_ button:UIButton){
        let searchVC = SearchViewController()
        searchVC.keyWord = searchArr[button.tag]
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
}
extension MainViewController{
    
    fileprivate func creatView(){
        
        let searchView = UIView()
        searchView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.08)
        self.view.addSubview(searchView)
        
        searchTextField.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH-40-SCREEN_HEIGHT*0.06, height: SCREEN_HEIGHT*0.06)
        searchTextField.placeholder = "SEARCH"
        searchTextField.delegate = self
        searchView.addSubview(searchTextField)
        
        let searchBtn = UIButton(type: .custom)
        searchBtn.frame = CGRect(x: SCREEN_WIDTH - SCREEN_HEIGHT*0.04 - 20, y: SCREEN_HEIGHT*0.02, width: SCREEN_HEIGHT*0.04, height: SCREEN_HEIGHT*0.04)
        searchBtn.setImage(UIImage(named: "menu_search"), for: UIControlState())
        searchBtn.addTarget(self, action: #selector(searchBtnCLick), for: .touchUpInside)
        searchView.addSubview(searchBtn)
        
        
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        
        myTableView.register(MainTableViewCell.self, forCellReuseIdentifier: MAINTABLEVIEWCELL)
        
        myTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { 
            self.dataArray.removeAllObjects()
            SVProgressHUD.show(withStatus: "Loading...")
            self.getData()
            self.getShoppongCartData()
            
        })
        
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        mySearchView.isHidden = false
        return true
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        mySearchView.isHidden = true
        let searchVC = SearchViewController()
        searchVC.keyWord = searchTextField.text!
        self.navigationController?.pushViewController(searchVC, animated: true)
        return true
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MAINTABLEVIEWCELL)
        
        let mainModel = self.dataArray[indexPath.row]as?MainDataModel
        (cell as? MainTableViewCell)?.model = mainModel
        
        
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if sideMenuViewController()?.menuContainerView?.currentSideMenuState == KVSideMenu.SideMenuState.right{
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick(_:)))
            myTableView.addGestureRecognizer(tap)
            return
        }
        
        let model = self.dataArray[indexPath.row] as? MainDataModel
        let productVC = ProductListViewController()
        productVC.title = self.productVCTitleArray[indexPath.row]
        productVC.cPathStr = (model?.cPath)!
        productVC.shoppingCarNumber = self.shoppingCarNumber
        self.navigationController?.pushViewController(productVC, animated: true)
    }
    
    
    func tapClick(_ tap:UITapGestureRecognizer){
        if sideMenuViewController()?.menuContainerView?.currentSideMenuState == KVSideMenu.SideMenuState.right{
            self.sideMenuViewController()?.menuContainerView?.toggleRightSideMenu()
        }else{
            myTableView.removeGestureRecognizer(tap)
        }
    }
    
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_HEIGHT*0.4
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    
    
    func searchBtnCLick(){
        let searchVC = SearchViewController()
        searchVC.keyWord = searchTextField.text!
        self.navigationController?.pushViewController(searchVC, animated: true)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
        mySearchView.isHidden = true
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}









